package org.example.day12;

import java.util.Calendar;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.15 awaitUntil(Date deadline)
 *      作用: 放弃锁进行等待，等待时间最长不超过deadline，如果deadline之前被唤醒就继续执行，如果deadline时还没被唤醒，则自己唤醒自己.
 **/
public class MyThread2 {
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    public void waitMethod(){
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.SECOND,10);
            lock.lock();
            System.out.println("wait begin tinme = " + System.currentTimeMillis());
            condition.awaitUntil(calendar.getTime());
            System.out.println("wait end tinme = " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void notifyMethod(){
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.SECOND,10);
            lock.lock();
            System.out.println("notify begin tinme = " + System.currentTimeMillis());
            condition.signalAll();
            System.out.println("notify end tinme = " + System.currentTimeMillis());
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread2 m2 = new MyThread2();
        Thread2A ta = new Thread2A(m2);
        ta.start();
        Thread.sleep(2000);
        Thread2B tb = new Thread2B(m2);
        tb.start();
    }
}

class Thread2A extends Thread{
    private MyThread2 m2;

    public Thread2A(MyThread2 m2) {
        this.m2 = m2;
    }

    @Override
    public void run() {
        m2.waitMethod();
    }
}
class Thread2B extends Thread{
    private MyThread2 m2;

    public Thread2B(MyThread2 m2) {
        this.m2 = m2;
    }

    @Override
    public void run() {
        m2.notifyMethod();
    }
}
